<!--
 * @Author: your name
 * @Date: 2021-08-10 15:32:03
 * @LastEditTime: 2021-08-16 11:49:53
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>快速排序</title>
</head>

<body>
  <p>
    把数组一分为三
  </p>

  <script>
    const utils = {
      swap(array, a, b) {
        [array[a], array[b]] = [array[b], array[a]]
      },
      randomNum() {
        return Math.floor(Math.random() * 15)
      },
      randomArray() {
        return Array.from(Array(this.randomNum()), _ => this.randomNum())
      }
    }

    function partition(array, start, end) {
      // j变量相当于记录右侧的长度
      let j = start
      let index = Math.floor(Math.random() * (end - start + 1) + start)

      utils.swap(array, index, end)
      let pivot = array[end]
      for (let i = start; i <= end; i++) {
        if (array[i] <= pivot) {
          utils.swap(array, i, j++)
        }
      }
      return j - 1
    }

    function quickSort(array, start = 0, end = array.length - 1) {
      if (end - start <= 0) return array
      let pivotIndex = partition(array, start, end)

      // [上次分界的左侧][上次分界][上次分界的右侧]
      quickSort(array, start, pivotIndex - 1) // end = 上次分界的右侧
      quickSort(array, pivotIndex + 1, end) // start = 上次分界的左侧
      return array
    }

    let array = utils.randomArray()
    console.log(quickSort([11, 13, 1, 7, 2, 4, 10, 14, 11, 1, 8, 12, 12]))

  </script>
</body>

</html>